package com.jzo2o.health.listener;

import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.health.constant.TradeConstants;
import com.jzo2o.health.enums.OrderPayStatusEnum;
import com.jzo2o.health.model.domain.Orders;
import com.jzo2o.health.model.dto.request.OrdersCancelReqDTO;
import com.jzo2o.health.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 监听mq消息，接收支付结果
 *
 * @author itcast
 **/
@Slf4j
@Component
public class TradeStatusListener {

    /**
     * 更新支付结果
     * 支付成功
     *
     * @param msg 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = TradeConstants.MQ_TRADE_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg) {
        log.info("接收到支付结果状态的消息 ({})-> {}", MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS, msg);

    }

    @Resource
    private IOrdersService ordersService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstants.Queues.ORDERS_CANCEL_QUEUE),
            exchange = @Exchange(value = MqConstants.Exchanges.ORDERS, delayed = "true"),
            key = MqConstants.RoutingKeys.ORDERS_CANCEL_KEY))
    public void listenNoPayOrder(String msg) {
        // 1. 判断订单id是否存在
        if (ObjectUtils.isNull(msg)) {
            return;
        }
        Long orderId = Long.valueOf(msg);
        // 2. 判断订单是否存在
        Orders orders = ordersService.getById(orderId);
        if (ObjectUtils.isNull(orders)) {
            return;
        }
        // 3. 判断订单是否是未支付
        if (ObjectUtils.notEqual(orders.getPayStatus(), OrderPayStatusEnum.NO_PAY.getStatus())) {
            return;
        }

        // 4. 取消订单
        OrdersCancelReqDTO dto = new OrdersCancelReqDTO();
        dto.setId(orderId);
        dto.setCancelReason("超时未支付自动取消");
        ordersService.cancel(dto,true);
        log.info("[超时未支付自动取消订单]取消完毕，订单id：{}", orderId);
    }
}
